﻿/*********************************************
 创建者：  dmhai
 创建时间：2017-05-12
 功能说明：我的配货
 ********************************************/
using com.nm.ApiServer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Systems;
using com.nm.Helper;
using com.nm.library.Helper;
using DistributeAPI.Model;
using george.Data;
using george.Helper;
using NHibernateVertica;
using Vertica.Data.VerticaClient;
using com.nm.library;

namespace DistributeAPI
{
    [Description("我的配货")]
    public class DCTaskMasteHandler : BaseHandler
    {
        public VerticaDataHelper Helper { get; set; } = new VerticaDataHelper();

        #region GetList

        [MustLogin]
        [Description("获取店铺首配深度列表")]
        [JsonType]
        [ReturnType(typeof(PaperData<DCTaskMasteModel.ListModel>))]
        public ApiResult GetList(DCTaskMasteModel.QueryModel param)
        {
            try
            {

                //构造SQL
                var sqlStr = @"select {0} from ( 
select tm.CompanyID,tm.TaskBillNo,tm.TaskType,tm.Operator,tm.OperateDate,tm.Finishdate,tm.PushBillDate,tm.TaskFlag,tm.StockID,bs.StockName,
row_number()over(order by tm.CompanyID,tm.TaskBillNo,tm.TaskType,tm.Operator,tm.OperateDate) as rowIndex
from ngoods.ngoods_DC_TaskMaster tm
left join nods.nods_erp_Bas_Stock as bs
ON tm.StockID = bs.StockID and tm.ExtrSource=bs.ExtrSource and tm.CompanyID=bs.CompanyID 
{1}
order by tm.OperateDate desc, tm.Finishdate desc
) table1 
";
                string whereStr = $"where  tm.ExtrSource='{UserInfo.UserExtrSource}' and tm.CompanyID='{UserInfo.UserCompanyId}' " +
                                    $" and tm.TaskType = {param.TaskType} " +
                                  $"and tm.OperateDate >= '{param.DateBegin}' and tm.OperateDate <= '{param.DateEnd}'";
                if (param.TaskFlag != 0)
                {
                    whereStr += " and tm.TaskFlag = " + param.TaskFlag;
                }
                //非管理员按用户ID筛选数据
                if (!MustAdminAttribute.Check(this.UserId.ToString()))
                    whereStr += " and tm.Operator=" + this.UserId;
                //获取总条数
                var countSql = string.Format(sqlStr, "count(1)", whereStr);
                var cmd = Helper.GetSqlStringCommand(countSql);
                var count = Convert.ToInt32(Helper.ExecuteScalar(cmd));

                //获取数据集
                var result = PaperData<DCTaskMasteModel.ListModel>.Create(count, param.Size, param.Page);
                var listSql = string.Format(sqlStr, "*", whereStr);
                if (param.Page != 0 && param.Size != 0)
                {
                    listSql += string.Format($@" where rowIndex BETWEEN ({param.Page}-1)*{param.Size}+1 AND {param.Page}*{param.Size} ");
                }
                var sys = new SysEntities();
                var dt = Helper.ExecuteDataTable(new VerticaCommand(listSql, null));

                result.Items = ModelConvertHelper<DCTaskMasteModel.ListModel>.ConvertToModel(dt);
                result.Items = (from d in result.Items
                                join u in sys.sys_users on d.Operator equals u.UserID.ToString()
                                select new { d, u }).ToList().Select(t => new DCTaskMasteModel.ListModel()
                                {
                                    ExtrSource = t.d.ExtrSource,
                                    CompanyID = t.d.CompanyID,
                                    TaskBillNo = t.d.TaskBillNo,
                                    TaskType = t.d.TaskType,
                                    Operator = t.d.Operator,
                                    OperatorName = t.u.UserName,
                                    OperateDate = t.d.OperateDate,
                                    Finishdate = t.d.Finishdate,
                                    PushBillDate = t.d.PushBillDate,
                                    TaskFlag = t.d.TaskFlag,
                                    StockID = t.d.StockID,
                                    StockName = t.d.StockName
                                }).ToList();
                return Success(result);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        #endregion

        #region Update

        [MustLogin]
        [Description("更新我的配货-作废")]
        [ReturnType(typeof(int), "0－成功")]
        public ApiResult Update([ParamDescription("任务单号")] string TaskBillNo = "")
        {

            #region 前端参数验证

            if (string.IsNullOrWhiteSpace(TaskBillNo))
            {
                return Error("任务单号解析失败，请刷新重试");
            }

            #endregion

            //要哦改操作员么?Operator = '',OperateDate = ''
            var sql = $@"update ngoods.ngoods_DC_TaskMaster 
set TaskFlag = -1
where   ExtrSource='{UserInfo.UserExtrSource}' and CompanyID='{UserInfo.UserCompanyId}' and TaskBillNo = '{TaskBillNo}'
";
            int n = Helper.ExecuteNonQuery(new VerticaCommand(sql));
            if (n > 0)
            {
                return Success(0);
            }
            return Error("更新失败,请重试");
        }

        #endregion

    }




}
